package com.example.toastqrcode;

import java.util.Hashtable;

import android.graphics.Bitmap;
import android.util.Log;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

public class GenerateQRCode
{
	private static final String TAG = "QRCodeDemo";
	private int QR_WIDTH = 400;
	private int QR_HEIGHT = 400;
	
	public GenerateQRCode(int width, int height)
	{
		if(width > 0 )
			QR_WIDTH = width;
		if(height > 0)
			QR_HEIGHT = height;
	}
	
	
	public Bitmap CreateQRCode(String url)
	{
		  
			try
			{
				//鍒ゆ柇URL鍚堟硶鎬�
				if (url == null || "".equals(url) || url.length() < 1)
				{
					return null;
				}
				Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
				hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
				
				//鍥惧儚鏁版嵁杞崲锛屼娇鐢ㄤ簡鐭╅樀杞崲
				BitMatrix bitMatrix = new QRCodeWriter().encode(url, BarcodeFormat.QR_CODE, QR_WIDTH, QR_HEIGHT, hints);
				int[] pixels = new int[QR_WIDTH * QR_HEIGHT];
				
				//涓嬮潰杩欓噷鎸夌収浜岀淮鐮佺殑绠楁硶锛岄�涓敓鎴愪簩缁寸爜鐨勫浘鐗囷紝
				for (int y = 0; y < QR_HEIGHT; y++)
				{
					for (int x = 0; x < QR_WIDTH; x++)
					{
						if (bitMatrix.get(x, y))
						{
							pixels[y * QR_WIDTH + x] = 0xff000000;
						}
						else
						{
							pixels[y * QR_WIDTH + x] = 0xffffffff;
						}
					}
				}
				//鐢熸垚浜岀淮鐮佸浘鐗囩殑鏍煎紡锛屼娇鐢ˋRGB_8888
				Bitmap bitmap = Bitmap.createBitmap(QR_WIDTH, QR_HEIGHT, Bitmap.Config.ARGB_8888);
				bitmap.setPixels(pixels, 0, QR_WIDTH, 0, 0, QR_WIDTH, QR_HEIGHT);
				 return bitmap;
			}
			catch (WriterException e)
			{
				e.printStackTrace();
			}

			return null;
    }
}